﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using ZX.DBModule;
using ZX.Common;
using ZX.BLL.Extend;
using System.Web.SessionState;


namespace ZX.WebApp.AjaxData
{
    //用于业务数据保存
    //用于调用业务逻辑
    
    
    /// <summary>
    /// PostHandler 的摘要说明
    /// </summary>
    public class datasave : IHttpHandler,IRequiresSessionState
    {
        
        public void ProcessRequest(HttpContext context)
        {
            PostData postData = new PostData();
            using (StreamReader sr = new StreamReader(context.Request.InputStream))
            {
                postData = JsonConvert.DeserializeObject<PostData>(sr.ReadToEnd());
            }
            BaseEntity instance = null;
            try
            {
                instance = JsonConvert.DeserializeObject(HttpUtility.UrlDecode(postData.instance), Globals.getEntity(postData.name).GetType()) as BaseEntity;
                //if (instance is DataEditTemplate)
                //{
                //    DataEditTemplate _instanace = ((DataEditTemplate)instance);
                //    _instanace.HtmlContent = HttpUtility.UrlDecode(_instanace.HtmlContent);
                //}
            }
            catch(Exception e)
            {

            }
            if (instance == null)
            {
                instance = Globals.JSONtoObject(postData.name, HttpUtility.UrlDecode(postData.instance)) as BaseEntity;
            }
            switch (postData.name)
            {
                default:
                    break;
            }
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(instance);
            if (postData.action=="insert")
            {
                bll.Insert();
            }
            else
            {
                bll.Update();
            }
            
            context.Response.ContentType = "text/plain";
            context.Response.Write(postData.name);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        

    }
}